<!DOCTYPE html>
<html>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="utf-8">
  

  
  <title>spring boot 构架restful风格的api | Hexo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="SpringBoot构建Restful风格API @Controller：修饰class，用来创建处理http请求的对象  @RestController：Spring4之后加入的注解，原来在@Controller中返回json需要@ResponseBody来配合，如果直接用@RestController替代@Controller就不需要再配置@ResponseBody，默认返回json格式。">
<meta name="keywords" content="springboot">
<meta property="og:type" content="article">
<meta property="og:title" content="spring boot 构架restful风格的api">
<meta property="og:url" content="http://yoursite.com/2018/10/12/2018-06-17-SpringBoot2构建RestfulAPI/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="SpringBoot构建Restful风格API @Controller：修饰class，用来创建处理http请求的对象  @RestController：Spring4之后加入的注解，原来在@Controller中返回json需要@ResponseBody来配合，如果直接用@RestController替代@Controller就不需要再配置@ResponseBody，默认返回json格式。">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://p1aoqp63y.bkt.clouddn.com/springbootrestfulapi-1.png">
<meta property="og:updated_time" content="2018-11-01T14:24:04.958Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="spring boot 构架restful风格的api">
<meta name="twitter:description" content="SpringBoot构建Restful风格API @Controller：修饰class，用来创建处理http请求的对象  @RestController：Spring4之后加入的注解，原来在@Controller中返回json需要@ResponseBody来配合，如果直接用@RestController替代@Controller就不需要再配置@ResponseBody，默认返回json格式。">
<meta name="twitter:image" content="http://p1aoqp63y.bkt.clouddn.com/springbootrestfulapi-1.png">
  
    <link rel="alternate" href="/org/atom.xml" title="Hexo" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/org/css/style.css">
</head>
</html>
<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/org/" id="logo">Hexo</a>
      </h1>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/org/">Home</a>
        
          <a class="main-nav-link" href="/org/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/org/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="Search"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-2018-06-17-SpringBoot2构建RestfulAPI" class="article article-type-post" itemscope="" itemprop="blogPost">
  <div class="article-meta">
    <a href="/org/2018/10/12/2018-06-17-SpringBoot2构建RestfulAPI/" class="article-date">
  <time datetime="2018-10-12T09:03:30.000Z" itemprop="datePublished">2018-10-12</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      spring boot 构架restful风格的api
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="SpringBoot构建Restful风格API"><a href="#SpringBoot构建Restful风格API" class="headerlink" title="SpringBoot构建Restful风格API"></a>SpringBoot构建Restful风格API</h2><ul>
<li><p><code>@Controller</code>：修饰class，用来创建处理http请求的对象</p>
</li>
<li><p><code>@RestController</code>：Spring4之后加入的注解，原来在<code>@Controller</code>中返回json需要<code>@ResponseBody</code>来配合，如果直接用<code>@RestController</code>替代<code>@Controller</code>就不需要再配置<code>@ResponseBody</code>，默认返回json格式。</p>
</li>
<li><p><code>@RequestMapping</code>：配置url映射</p>
<a id="more"></a>
</li>
</ul>
<p>下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API，配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试。 </p>
<p><img src="http://p1aoqp63y.bkt.clouddn.com/springbootrestfulapi-1.png" alt="img"></p>
<p>User实体定义：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">public class User &#123; </span><br><span class="line"> </span><br><span class="line">    private Long id; </span><br><span class="line">    private String name; </span><br><span class="line">    private Integer age; </span><br><span class="line"> </span><br><span class="line">    // 省略setter和getter </span><br><span class="line">     </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实现对User对象的操作接口</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line">@RestController </span><br><span class="line">@RequestMapping(value=&quot;/users&quot;)     // 通过这里配置使下面的映射都在/users下 </span><br><span class="line">public class UserController &#123; </span><br><span class="line"> </span><br><span class="line">    // 创建线程安全的Map </span><br><span class="line">    static Map&lt;Long, User&gt; users = Collections.synchronizedMap(new HashMap&lt;Long, User&gt;()); </span><br><span class="line"> </span><br><span class="line">    @RequestMapping(value=&quot;/&quot;, method=RequestMethod.GET) </span><br><span class="line">    public List&lt;User&gt; getUserList() &#123; </span><br><span class="line">        // 处理&quot;/users/&quot;的GET请求，用来获取用户列表 </span><br><span class="line">        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递 </span><br><span class="line">        List&lt;User&gt; r = new ArrayList&lt;User&gt;(users.values()); </span><br><span class="line">        return r; </span><br><span class="line">    &#125; </span><br><span class="line"> </span><br><span class="line">    @RequestMapping(value=&quot;/&quot;, method=RequestMethod.POST) </span><br><span class="line">    public String postUser(@ModelAttribute User user) &#123; </span><br><span class="line">        // 处理&quot;/users/&quot;的POST请求，用来创建User </span><br><span class="line">        // 除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数 </span><br><span class="line">        users.put(user.getId(), user); </span><br><span class="line">        return &quot;success&quot;; </span><br><span class="line">    &#125; </span><br><span class="line"> </span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.GET) </span><br><span class="line">    public User getUser(@PathVariable Long id) &#123; </span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的GET请求，用来获取url中id值的User信息 </span><br><span class="line">        // url中的id可通过@PathVariable绑定到函数的参数中 </span><br><span class="line">        return users.get(id); </span><br><span class="line">    &#125; </span><br><span class="line"> </span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.PUT) </span><br><span class="line">    public String putUser(@PathVariable Long id, @ModelAttribute User user) &#123; </span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的PUT请求，用来更新User信息 </span><br><span class="line">        User u = users.get(id); </span><br><span class="line">        u.setName(user.getName()); </span><br><span class="line">        u.setAge(user.getAge()); </span><br><span class="line">        users.put(id, u); </span><br><span class="line">        return &quot;success&quot;; </span><br><span class="line">    &#125; </span><br><span class="line"> </span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.DELETE) </span><br><span class="line">    public String deleteUser(@PathVariable Long id) &#123; </span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的DELETE请求，用来删除User </span><br><span class="line">        users.remove(id); </span><br><span class="line">        return &quot;success&quot;; </span><br><span class="line">    &#125; </span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>下面针对该Controller编写测试用例验证正确性，具体如下。当然也可以通过浏览器插件等进行请求提交验证。 </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line">package com.example.demo.controller;</span><br><span class="line"></span><br><span class="line">import com.example.demo.entity.User;</span><br><span class="line">import org.springframework.web.bind.annotation.*;</span><br><span class="line"></span><br><span class="line">import java.util.*;</span><br><span class="line"></span><br><span class="line">@RestController</span><br><span class="line">@RequestMapping(value=&quot;/users&quot;)     // 通过这里配置使下面的映射都在/users下</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">    // 创建线程安全的Map</span><br><span class="line">    static Map&lt;Long, User&gt; users = Collections.synchronizedMap(new HashMap&lt;Long, User&gt;());</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value=&quot;/&quot;, method=RequestMethod.GET)</span><br><span class="line">    public List&lt;User&gt; getUserList() &#123;</span><br><span class="line">        // 处理&quot;/users/&quot;的GET请求，用来获取用户列表</span><br><span class="line">        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递</span><br><span class="line">        List&lt;User&gt; r = new ArrayList&lt;User&gt;(users.values());</span><br><span class="line">        return r;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value=&quot;/&quot;, method=RequestMethod.POST)</span><br><span class="line">    public String postUser(@ModelAttribute User user) &#123;</span><br><span class="line">        // 处理&quot;/users/&quot;的POST请求，用来创建User</span><br><span class="line">        // 除了@ModelAttribute绑定参数之外，还可以通过@RequestParam从页面中传递参数</span><br><span class="line">        users.put(user.getId(), user);</span><br><span class="line">        return &quot;success&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.GET)</span><br><span class="line">    public User getUser(@PathVariable Long id) &#123;</span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的GET请求，用来获取url中id值的User信息</span><br><span class="line">        // url中的id可通过@PathVariable绑定到函数的参数中</span><br><span class="line">        return users.get(id);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.PUT)</span><br><span class="line">    public String putUser(@PathVariable Long id, @ModelAttribute User user) &#123;</span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的PUT请求，用来更新User信息</span><br><span class="line">        User u = users.get(id);</span><br><span class="line">        u.setName(user.getName());</span><br><span class="line">        u.setAge(user.getAge());</span><br><span class="line">        users.put(id, u);</span><br><span class="line">        return &quot;success&quot;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    @RequestMapping(value=&quot;/&#123;id&#125;&quot;, method=RequestMethod.DELETE)</span><br><span class="line">    public String deleteUser(@PathVariable Long id) &#123;</span><br><span class="line">        // 处理&quot;/users/&#123;id&#125;&quot;的DELETE请求，用来删除User</span><br><span class="line">        users.remove(id);</span><br><span class="line">        return &quot;success&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>至此，我们通过引入web模块（没有做其他的任何配置），就可以轻松利用Spring MVC的功能，以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。其中同时介绍了Spring MVC中最为常用的几个核心注解：<code>@Controller</code>,<code>@RestController</code>,<code>RequestMapping</code>以及一些参数绑定的注解：<code>@PathVariable</code>,<code>@ModelAttribute</code>,<code>@RequestParam</code>等。 </p>
<h2 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h2><p><a href="https://gitee.com/anweb/SpringBoot-Learning" target="_blank" rel="noopener">源码下载-</a></p>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2018/10/12/2018-06-17-SpringBoot2构建RestfulAPI/" data-id="cjoztxu5z00271wijacrcakzo" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/org/tags/springboot/">springboot</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/org/2018/10/12/2018-06-17-SpringBoot web开发-Thymeleaf模板引擎/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          SpringBoot web开发-Thymeleaf模板引擎
        
      </div>
    </a>
  
  
    <a href="/org/2018/10/12/2018-06-17-SpringBoot中使用Spring-data-jpa/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">SpringBoot中使用Spring-data-jpa</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tags</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/SVN/">SVN</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/Spring-secrity/">Spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hexo/">hexo</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/hibenrate/">hibenrate</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jekyll/">jekyll</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/jenkins/">jenkins</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/redis/">redis</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/shiro/">shiro</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spingMVC/">spingMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-cloud/">spring-cloud</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/spring-secrity/">spring-secrity</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springMVC/">springMVC</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/springboot/">springboot</a></li><li class="tag-list-item"><a class="tag-list-link" href="/org/tags/生活/">生活</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget tagcloud">
      <a href="/org/tags/SVN/" style="font-size: 12px;">SVN</a> <a href="/org/tags/Spring-secrity/" style="font-size: 10px;">Spring-secrity</a> <a href="/org/tags/hexo/" style="font-size: 10px;">hexo</a> <a href="/org/tags/hibenrate/" style="font-size: 10px;">hibenrate</a> <a href="/org/tags/jekyll/" style="font-size: 10px;">jekyll</a> <a href="/org/tags/jenkins/" style="font-size: 10px;">jenkins</a> <a href="/org/tags/redis/" style="font-size: 16px;">redis</a> <a href="/org/tags/shiro/" style="font-size: 18px;">shiro</a> <a href="/org/tags/spingMVC/" style="font-size: 10px;">spingMVC</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring cloud</a> <a href="/org/tags/spring-cloud/" style="font-size: 10px;">spring-cloud</a> <a href="/org/tags/spring-secrity/" style="font-size: 12px;">spring-secrity</a> <a href="/org/tags/springMVC/" style="font-size: 14px;">springMVC</a> <a href="/org/tags/springboot/" style="font-size: 20px;">springboot</a> <a href="/org/tags/生活/" style="font-size: 10px;">生活</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Archives</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/11/">November 2018</a></li><li class="archive-list-item"><a class="archive-list-link" href="/org/archives/2018/10/">October 2018</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/org/2018/11/27/redis07-zookeeper-kafka集群部署以及如何使用简单介绍/">redis07-zookeeper+kafka集群部署以及如何使用简单介绍</a>
          </li>
        
          <li>
            <a href="/org/2018/11/13/redis06-cluster实现高可用性/">redis06-cluster实现高可用性</a>
          </li>
        
          <li>
            <a href="/org/2018/11/12/redis05-在项目中搭建读写分-高可用-多master的redis-cluster集群/">redis05-在项目中搭建读写分+高可用+多master的redis cluster集群</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/在项目中用经典的三节点方式部署哨兵集群-笔记/">在项目中用经典的三节点方式部署哨兵集群-笔记</a>
          </li>
        
          <li>
            <a href="/org/2018/11/05/redis哨兵的多个核心底层原理-笔记/">redis哨兵的多个核心底层原理-笔记</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 John Doe<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/org/" class="mobile-nav-link">Home</a>
  
    <a href="/org/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//code.jquery.com/jquery-2.0.3.min.js"></script>


  <link rel="stylesheet" href="/org/fancybox/jquery.fancybox.css">
  <script src="/org/fancybox/jquery.fancybox.pack.js"></script>


<script src="/org/js/script.js"></script>



  </div>
</body>
</html>